package com.cci.kangdao.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.CustomerEngineRelDao;
import com.cci.kangdao.dao.DictionariesTDao;
import com.cci.kangdao.dao.EngineMasterDataMapper;
import com.cci.kangdao.dao.LoginDao;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dto.response.MedbFleet;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.WwidFleetService;
import com.cci.kangdao.utilTool.AESTool;
import com.cci.kangdao.utilTool.HttpUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.ParameterTool;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Service()
public class WwidFleetServiceImpl implements WwidFleetService {
    private String WWID_EMISSION_LEVEL_LIST = "WWIDEmissionLevelList";

    private Logger log = Logger.getLogger(this.getClass().getName());

    @Resource
    private DictionariesTDao dictionariesTDao;
    @Resource
    private CustomerEngineRelDao customerEngineRelDao;
    @Autowired
    private RedisClientUtils redisClientUtils;
    @Autowired
    private EngineMasterDataMapper engineMasterDataMapper;

    @Resource
    private LoginDao loginDao;
    @Value("${medbSign}")
    private String SIGN;
    @Value("${medbWWID}")
    private String MEDB_WWID;
    @Value("${medbTokenUrl}")
    private String MEDB_TOKEN_URL;
    @Value("${medbFleetList}")
    private String MEDB_FLEET_LIST;
    @Value("${medbEsnList}")
    private String MEDB_ESN_LIST;
    private String MEDB_REDIS_KEY = "MEDB_REDIS_KEY";//redis  key


    @Override
    public ModelAndView getCustomerEngineRelByKeyWord(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        this.getParams(userT.getId(), map);
        if (userT.getType() != 2) {
            ParameterTool.writeErrorResponse(response, -99, "只有wwid用户才能查询");
            return null;
        }
        if (!map.containsKey("paramList")) {
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(new ArrayList<>());
            ParameterTool.writeSuccessResponse(response, pageInfo);
            return null;
        }
        PageHelper.startPage(MapUtils.getInteger(map, "page", 1), MapUtils.getInteger(map, "pageSize", 50));
        PageHelper.orderBy("   orderNum DESC ,HB_CREATE_TIME DESC");
        LocalDateTime realCurrentLocalTime = LocalTimeUtil.getRealCurrentLocalDateTime();
        LocalDateTime localSubtractThreeDate = realCurrentLocalTime.minus(3, ChronoUnit.MONTHS);
        LocalDateTime localSubtractFourDate =  realCurrentLocalTime.minus(4, ChronoUnit.MONTHS);
        log.error("localSubtractThreeDate:"+localSubtractThreeDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        log.error("localSubtractFourDate:"+localSubtractFourDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        map.put("localSubtractThreeDate",localSubtractThreeDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        map.put("localSubtractFourDate",localSubtractFourDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        List<Map<String, Object>> customerEngineRelList = customerEngineRelDao.getCustomerEngineRelByKeyWord(map);

        Map<String, Map<String, Object>> fleetEmissionLevelDicListMap = dictionariesTDao.getDicListByDtableName("fleetEmissionLevel");
        Map<String, Map<String, Object>> fleetFuelTypeDicListMap = dictionariesTDao.getDicListByDtableName("fleetFuelType");
        //获取字典表应用类型map(调用cip接口返回的应用类型枚举值)
        if (CollectionUtils.isNotEmpty(customerEngineRelList)) {
            for (Map<String, Object> stringObjectMap : customerEngineRelList) {
                String fuelType = MapUtils.getString(stringObjectMap, "engineFuelType");
                String emissionLevel = MapUtils.getString(stringObjectMap, "relBulletinTelAboEmissionLevel");
                if (MapUtils.isNotEmpty(fleetEmissionLevelDicListMap) && StringUtils.isNotEmpty(emissionLevel) && fleetEmissionLevelDicListMap.containsKey(emissionLevel)) {
                    Map<String, Object> fleetEmissionLevelDicMap = MapUtils.getObject(fleetEmissionLevelDicListMap, emissionLevel);
                    if (MapUtils.isNotEmpty(fleetEmissionLevelDicMap)) {
                        stringObjectMap.put("EsnApplicationType", MapUtils.getIntValue(fleetEmissionLevelDicMap, "DInt", -1));
                    }
                }
                //获取字典表动力类型ma(调用cip接口返回的应用类型枚举值)
                if (MapUtils.isNotEmpty(fleetFuelTypeDicListMap) && StringUtils.isNotEmpty(fuelType) && fleetFuelTypeDicListMap.containsKey(fuelType)) {
                    Map<String, Object> fleetFuelTypeDicMap = MapUtils.getObject(fleetFuelTypeDicListMap, fuelType);
                    if (MapUtils.isNotEmpty(fleetFuelTypeDicMap)) {
                        stringObjectMap.put("EsnPowerType", MapUtils.getIntValue(fleetFuelTypeDicMap, "DInt", -1));
                    }
                }
            }
        }
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(customerEngineRelList);
        ParameterTool.writeSuccessResponse(response, pageInfo);
        return null;
    }

    /**
     * 获取 comppanyNo 的参数
     *
     * @param id
     * @param map
     */

    public void getParams(Long id, Map<String, Object> map) {
        UserT userT = UserThreadLocal.get();
        UserT userAndGroupNoByAdUserId = loginDao.getUserAndGroupNoByAdUserId(userT.getId());
        List<String> paramList = new ArrayList<>();
        if (StringUtils.isNotBlank(userAndGroupNoByAdUserId.getUserGoupNo())) {
            if ("G0001".equals(userAndGroupNoByAdUserId.getUserGoupNo()) || "G0028".equals(userAndGroupNoByAdUserId.getUserGoupNo())) {
                paramList = Arrays.asList("ACPL", "BFCEC", "CCEC", "CCI", "DCEC", "GCIC", "XCEC", "NPSH");
            } else if ("G0002".equals(userAndGroupNoByAdUserId.getUserGoupNo())) {
                paramList = Arrays.asList("BFCEC");
            } else if ("G0003".equals(userAndGroupNoByAdUserId.getUserGoupNo())) {
                paramList = Arrays.asList("DCEC");
            } else if ("G0004".equals(userAndGroupNoByAdUserId.getUserGoupNo())) {
                paramList = Arrays.asList("XCEC");
            } else if ("G0016".equals(userAndGroupNoByAdUserId.getUserGoupNo())) {
                paramList = Arrays.asList("CCEC");
            } else if ("G0017".equals(userAndGroupNoByAdUserId.getUserGoupNo())) {
                paramList = Arrays.asList("ACPL");
            } else if ("G0018".equals(userAndGroupNoByAdUserId.getUserGoupNo())) {
                paramList = Arrays.asList("GCIC");
            }
            if (CollectionUtils.isNotEmpty(paramList)) {
                map.put("paramList", paramList);
            }
            log.error("mapjson:"+JSON.toJSONString(paramList));
        }
    }

    /**
     * wwid 用户设备列表接口-------获取销售实体，平台,排放等级
     * 根据用户id获取设备列表
     *
     * @param map
     * @return
     */
    @Override
    public ModelAndView getSearchParams(Map<String, Object> map) {
        UserT userT = UserThreadLocal.get();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        Map<String, Object> data = new HashMap<>();
        this.getParams(userT.getId(), map);
        if (!map.containsKey("paramList")) {
            data.put("relSalesPlantList",new ArrayList<String>());
            data.put("relBulletinTelAboPlatFormList", new ArrayList<String>());
            data.put("relBulletinTelAboEmissionLevelList", new ArrayList<String>());
            ParameterTool.writeSuccessResponse(response, data);
            return null;
        }
        log.error("mapjson:"+JSON.toJSONString(map.get("paramList")));
        List<String> relSalesPlantList = engineMasterDataMapper.selectrelSalesPlantList(map);
        List<String> relBulletinTelAboPlatformList = engineMasterDataMapper.selectRelBulletinTelAboPlat(map);
        List<String> relBulletinTelAboEmissionLevelList = engineMasterDataMapper.selectrelBulletinTelAboEmissionLevel(map);
        data.put("relSalesPlantList", CollectionUtils.isNotEmpty(relSalesPlantList) ? relSalesPlantList : new ArrayList<String>());
        data.put("relBulletinTelAboPlatformList", CollectionUtils.isNotEmpty(relBulletinTelAboPlatformList) ? relBulletinTelAboPlatformList : new ArrayList<String>());
        data.put("relBulletinTelAboEmissionLevelList", CollectionUtils.isNotEmpty(relBulletinTelAboEmissionLevelList) ? relBulletinTelAboEmissionLevelList : new ArrayList<String>());
        ParameterTool.writeSuccessResponse(response, data);
        return null;
    }

    /**
     *b端 wwid  获取车队列表
     * @param map
     * @return
     */
    @Override
    public ModelAndView getfleetList(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        try{
            UserT userT = UserThreadLocal.get();
            if (userT.getType()!=2) {
                ParameterTool.writeErrorResponse(response, -99, "只有wwid用户才能查询");
                return null;
            }
            String token = this.getToken();
            if (StringUtils.isBlank(token)) {
                ParameterTool.writeErrorResponse(response, -99, "获取token失败");
                return null;
            }
            Integer pageSize = MapUtils.getInteger(map, "pageSize", 10);
            Integer pageNum = MapUtils.getInteger(map, "pageNum", 1);
            String keywords = MapUtils.getString(map, "keywords","");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("wwid", userT.getUserName());
            jsonObject.put("pageNum", pageNum);
            jsonObject.put("pageSize", pageSize);
            if (StringUtils.isNotBlank(keywords)) {
                jsonObject.put("fleetName", keywords);
            }
            Header tokenHeader = new BasicHeader("token", token);
            Header wwidHeader = new BasicHeader("wwid", MEDB_WWID);
            Header content = new BasicHeader("Content-Type", "application/json");
            String resultStr = HttpUtils.postJson(MEDB_FLEET_LIST, jsonObject.toString(), new ResponseHandler<String>() {
                @Override
                public String handleResponse(HttpResponse response)
                        throws IOException {
                    if (response.getStatusLine().getStatusCode() == 200) {
                        HttpEntity httpEntity = response.getEntity();
                        return EntityUtils.toString(httpEntity);
                    }else {
                        log.info("获取 MEDB_FLEET_LIST 失败；打印地址："+MEDB_FLEET_LIST+ "；token：" +token+ "；wwid：" +MEDB_WWID);
                        log.info("获取 MEDB_FLEET_LIST 失败；打印参数：" + jsonObject.toJSONString() + "；返回结果：" + response.toString() + "；token：" +MEDB_WWID);
                    }
                    return null;
                }
            }, tokenHeader, wwidHeader,content);
            if (StringUtils.isNotBlank(resultStr)) {
                log.error("获取 MEDB_FLEET_LIST-成功,打印地址"+MEDB_FLEET_LIST+ "；token：" +token+ "；wwid："+MEDB_WWID+ "；参数："+ jsonObject + "结果："+resultStr);
                JSONObject dataJson = JSONObject.parseObject(resultStr);
                Integer code = dataJson.getInteger("code");
                if (code!=null && code==0 && dataJson.get("data") != null) {
                    JSONObject dataObjectJson = JSONObject.parseObject(JSONObject.toJSONString(dataJson.get("data")));
                    if (dataObjectJson.get("dataList") != null) {
                        List<MedbFleet> fleets = JSONArray.parseArray(JSONArray.toJSONString(dataObjectJson.get("dataList")), MedbFleet.class);
                        if (CollectionUtils.isNotEmpty(fleets)) {
                            for (MedbFleet fleet : fleets) {
                                if (StringUtils.isNotBlank(fleet.getHeadName())) {
                                    fleet.setHeadName(AESTool.medbDecrypt(fleet.getHeadName()));
                                }
                                if (StringUtils.isNotBlank(fleet.getHeadPhone())) {
                                    fleet.setHeadPhone(AESTool.medbDecrypt(fleet.getHeadPhone()));
                                }
                                fleet.setSharingFlag(!userT.getUserName().equals(fleet.getCreatorWwid()));
                            }
                        }
                        dataObjectJson.put("dataList",fleets);
                    }
                    ParameterTool.writeSuccessResponse(response,dataObjectJson);
                    return null;
                }else {
                    String message = dataJson.getString("message");
                    ParameterTool.writeResponse(response,-997,message);
                    return null;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        ParameterTool.writeErrorResponse(response, -99, "查询数据失败");
        return null;
    }
    /**
     *b端 wwid  获取esn列表接口
     * @param map
     * @return
     */
    @Override
    public ModelAndView getEsnList(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String fleetId = MapUtils.getString(map, "fleetId");
        if (StringUtils.isBlank(fleetId)) {
            ParameterTool.writeErrorResponse(response, -99, "请输入fleetId");
            return null;
        }
        UserT userT = UserThreadLocal.get();

        String token = this.getToken();
        if (StringUtils.isBlank(token)) {
            ParameterTool.writeErrorResponse(response, -99, "获取token失败");
            return null;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("wwid", userT.getUserName());
        jsonObject.put("fleetId", fleetId);
        Header tokenHeader = new BasicHeader("token", token);
        Header wwidHeader = new BasicHeader("wwid", MEDB_WWID);
        String resultStr = HttpUtils.postJson(MEDB_ESN_LIST, jsonObject.toJSONString(), new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse response)
                    throws ClientProtocolException, IOException {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    return EntityUtils.toString(httpEntity);
                }else {
                    log.info("获取MEDB_ESN_LIST失败；打印参数：" + jsonObject.toJSONString() + "；返回结果：" + com.alibaba.fastjson.JSON.toJSONString(response.getEntity()));
                }
                return null;
            }
        }, tokenHeader, wwidHeader);
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject dataJson = JSONObject.parseObject(resultStr);
            if (StringUtils.isNotBlank(dataJson.getString("data"))) {
                List<String> esnList = JSONArray.parseArray(dataJson.getString("data"), String.class);
                if (CollectionUtils.isNotEmpty(esnList)) {
                    map.put("esnList", esnList);
                    List<Map<String, Object>> customerEngineRelList = customerEngineRelDao.getCustomerEngineRelByKeyWord(map);
                    ParameterTool.writeSuccessResponse(response, customerEngineRelList);
                    return null;
                }
                ParameterTool.writeSuccessResponse(response, dataJson.get("data"));
                return null;
            }
            ParameterTool.writeSuccessResponse(response, new ArrayList<>());
            return null;
        }
        return null;
    }

    public String getToken() {
        String token = this.requestToken();
        if (StringUtils.isBlank(token)) {
            token = this.requestToken();
        }
        return token;
    }

    public String requestToken() {
        String tokenStr = redisClientUtils.get(MEDB_REDIS_KEY);
        if (StringUtils.isNotBlank(tokenStr)) {
            return tokenStr;
        }
        String token = "";
        String paramToken = this.createSign(SIGN);
        Header tokenHeader = new BasicHeader("token", paramToken);
        Header wwidHeader = new BasicHeader("wwid", MEDB_WWID);
        try {
            String resultStr = HttpUtils.get(MEDB_TOKEN_URL, new ResponseHandler<String>() {
                @Override
                public String handleResponse(HttpResponse response)
                        throws ClientProtocolException, IOException {
                    if (response.getStatusLine().getStatusCode() == 200) {
                        HttpEntity httpEntity = response.getEntity();
                        return EntityUtils.toString(httpEntity);
                    }
                    return null;
                }
            }, tokenHeader, wwidHeader);
            if (StringUtils.isNotEmpty(resultStr)) {
                log.info("添加medbtoken成功；打印参数：无；header  token:" + paramToken + ",wwid " + MEDB_WWID + "；返回结果：" + resultStr);
                JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(resultStr);
                Integer code = jsonObject.getInteger("code");
                if (code!=null && code==0 && jsonObject.get("data")!=null) {
                    JSONObject jsonObjectData = com.alibaba.fastjson.JSON.parseObject(JSON.toJSONString(jsonObject.get("data")));
                    token = jsonObjectData.getString("token");
                    redisClientUtils.set(MEDB_REDIS_KEY, token, 20 * 60);
                }
            } else {
                log.info("添加medbtoken失败；打印参数：无；header  token:" + paramToken + ",wwid " + MEDB_WWID + "；返回结果：" + resultStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    public String createSign(String sign) {
        Algorithm al = Algorithm.HMAC256(sign);
        return JWT.create().withExpiresAt(new Date(System.currentTimeMillis() + 60 * 1000)).sign(al);
    }
}
